var app = getApp()
Page({
  data: {
    orderId: '',
    orderDetail: {},
    checkedCode:[],
    max_refund:0,
    suggest_refund:0,
    refund_list:[],
    reason:'',
    contact:'',
    tid:'',
    toid:'',
    reasonList:[{name:"无理由退换",id:0},{name:"质量问题",id:1}],
    selectedReasons:[],
    explain:'',
    imgs:[],
    num:1,
    currentIndex:0,
    source:'',
    reasonId:0,
    selected: false
  },
  onLoad: function (options) {
    let _this = this
    _this.setData({
      orderId: options.orderId,
      source: options.source
    })
    if(options.source=='ali') {
      var arr = []
      wx.request({
        url: app.globalData.requestUrl,
        data: {
          map:'applet_order_refund_reason',
          order_sn:options.orderId
        },
        success: function (res) { 
          if(res.data.ec==200) {
            arr = res.data.data
            _this.setData({
              reasonList: arr
            })
          }
        }
      })
    }
    
  },
  reasonChange(e){
    var bool = false
    if(this.data.source=='ali') {
      let reasonList = this.data.reasonList
      reasonList.map(val=>{
        if(val.id == e.detail.value) {
          bool = val.needVoucher?true:false;
        }
      })
      this.setData({
        reasonId:e.detail.value,
        selected: bool
      })
    }else {
      bool = e.detail.value==1?true:false;
      this.setData({
        selectedReasons:e.detail.value,
        selected: bool
      })
    }
  },
  tkMoneyChange: function (e) {
    let {max_refund} = this.data
    console.log(e)
    if(e.detail.value<=max_refund) {
      console.log(1)
      this.setData({
        suggest_refund: e.detail.value
      })
    }else {
      console.log(2)
      this.setData({
        suggest_refund: max_refund
      })
      wx.showToast({
        title: '已超过最大金额',
        icon:'none'
      })
    }
  },
  tkReasonChange: function (e) {
    this.setData({
      explain: e.detail.value
    });
  },
  tkContactChange: function (e) {
    this.setData({
      contact: e.detail.value
    })
  },
  // 上传图片
  chooseImg(){
    var that = this;
    var imgs = this.data.imgs;
    var imgurl = ''
    var imgName = ''
    if(that.data.source=='yanxuan') {
      imgurl = app.globalData.requestUrl+'&map=applet_order_refund_net_upload'
      imgName = 'net_file'
    }else if(that.data.source=='ali') {
      imgurl = app.globalData.requestUrl+'&map=applet_order_refund_ali_upload'
      imgName = 'ali_file'
    }
    wx.chooseImage({
      //count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var imgs = that.data.imgs;
        res.tempFilePaths.forEach(items=>{
          wx.showLoading({
            title: '正在上传中...',
          })
          wx.uploadFile({
            url: imgurl,
            filePath: items,
            name: imgName,
            header:{
              "content-type": "application/json"
            },
            success:function(res){
              let data = JSON.parse(res.data)
              if(data.ec==200) {
                imgs.push(data.data.url);
                that.setData({
                  imgs: imgs
                });
              }else {
                wx.showToast({
                  title: '上传失败'
                });
              }
              wx.hideLoading();
            },
            fail: (err) => {
              wx.hideLoading();
              this.imgList = res.
              that.setData({
                imgs: res.tempFilePaths[0]
              });
              console.error(err);
              wx.showToast({
                title: '上传失败'
              });
            }
          })
        })
      }
    });
  },
  // 减
  reduceNum(){
    if(this.data.num<=1){
      wx.showToast({
        title: '最小为1',
        duration:1000,
        icon:"none"
      })
      return
    }
    let num=this.data.num-1
    this.setData({
      num:num
    })
  },
  // 加
  addNum(){
    let num=this.data.num+1
    if(this.data.num>=this.data.orderDetail.goods[this.data.currentIndex].num){
      wx.showToast({
        title: '最大为'+this.data.orderDetail.goods[this.data.currentIndex].num,
        duration:1000,
        icon:"none"
      })
      return
    }
    this.setData({
      num:num
    })
  },
  // 删除图片
  removeImg(e){
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs
    });
  },
  // 预览图片
  previewImg(e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    //所有图片
    var imgs = this.data.imgs;
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },
  handleGoods(e){
    var index = e.currentTarget.dataset.index;
    console.log(index)
    this.setData({
      currentIndex:index
    })
  },
  submitRefund: function () {
    var that = this;
    var data = {};
    data.map = 'applet_order_refund';
    data.tid = that.data.tid;
    data.money = that.data.suggest_refund;
    data.explain = that.data.explain;
    data.contact = that.data.contact;
    data.reasonImg=JSON.stringify(that.data.imgs)
    data.toid=that.data.orderDetail.goods[that.data.currentIndex].toid
    data.num=that.data.num
    if(that.data.source=='ali') {
      data.reason_id = that.data.reasonId;
    }else if(that.data.source=='yanxuan') {
      data.tr_reason_status=that.data.selectedReasons
    }
    console.log(data)
    console.log(that.data)
    if (data.money == "") {
      wx.showToast({
        title: "请输入退款金额",
        duration:2000,
        icon:"none"
      })
      return;
    }
    if (parseFloat(data.money) > that.data.orderDetail.payment) {
      wx.showToast({
        title: "退款金额不能大于实际支付金额",
        duration:2000,
        icon:"none"
      })
      return;
    }
    if(that.data.source=='yanxuan') {
      if (data.tr_reason_status == "") {
        wx.showToast({
          title: "请先选择退款原因",
          duration:2000,
          icon:"none"
        })
        return;
      }
      if(data.tr_reason_status==1){
        if (data.reasonImg == "") {
          wx.showToast({
            title: "请输上传图片",
            duration:2000,
            icon:"none"
          })
          return;
        }
        if (data.explain == "") {
          wx.showToast({
            title: "请输入退款说明",
            duration:2000,
            icon:"none"
          })
          return;
        }
      }
    }else if(that.data.source=='ali') {
      if(data.reason_id=='') {
        wx.showToast({
          title: "请先选择退款原因",
          duration:2000,
          icon:"none"
        })
        return;
      }else {
        let reasonList = that.data.reasonList
        reasonList.map(val=>{
          if(val.id == data.reason_id) {
            if(val.needVoucher) {
              if (data.reasonImg == "") {
                wx.showToast({
                  title: "请输上传图片",
                  duration:2000,
                  icon:"none"
                })
                return;
              }
              if (data.explain == "") {
                wx.showToast({
                  title: "请输入退款说明",
                  duration:2000,
                  icon:"none"
                })
                return;
              }
            }
          }
        })
      }
    }
    
    if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(data.contact)) {
      wx.showToast({
        title: "请输入正确的手机号",
        duration:2000,
        icon:"none"
      })
      return;
    }
    
    //发起请求，获取列表列表
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 10000
    });
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        wx.hideToast();
        if (res.data.ec == 200) {
          wx.showToast({
            title: '申请成功！',
            duration:2000
          })
          that.onShow();
          setTimeout(wx.navigateBack,2000)
        } else {
          wx.hideToast();
          wx.showToast({
            title: res.data.em,
            duration:2000,
            icon:"none"
          })
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var orderid = that.data.orderId;
    this.setData({
      tid: orderid
    })
    //发起请求，获取列表列表
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 10000
    });
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_order_detail',
        tid: orderid
      },
      success: function (res) {
        if (res.data.ec == 200) {
          // var orderDetail = res.data.data
          // var refundAble = 0
          // orderDetail.goods.forEach(v => {
          //   if(v.ticket_info.wait_use){   //调试状态京东商品不存在这个属性
          //     refundAble += parseFloat(v.ticket_info.wait_use.max_refund)
          //   }
          // })
          // if (orderDetail.status == 3){
          //   refundAble += parseFloat(orderDetail.freight)
          // }
          that.setData({
            orderDetail: res.data.data,
            max_refund: res.data.data.payment,
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.em,
            showCancel: false
          });
        }
      },
      complete: function () {
        wx.hideToast();
      }
    });
  },

  checkboxChangeTicket:function(e){
    var { id, gid, price } = e.currentTarget.dataset;
    var refund_list = this.data.refund_list
    var arr = [{ id: id, gid: gid, price: price }]
    if (refund_list.length == 0){
      var total = this.data.suggest_refund + parseFloat(price)
      this.setData({
        suggest_refund: total,
        refund_list: arr
        })
    }else{
      var add = true;
      refund_list.forEach((v, index) => {
        if (v.id == id) {
          var total = this.data.suggest_refund
          total = total - parseFloat(v.price);
          refund_list.splice(index, 1);
          this.setData({
            suggest_refund: total,
            refund_list: refund_list
          })
          add = false
        }
      })
      if (add){
        var total = this.data.suggest_refund
        total += parseFloat(price)
        this.setData({
          suggest_refund: total,
          refund_list: arr.concat(refund_list)
        })
      }
    }
    console.log(this.data.refund_list)
    this.setData({
      checkedCode:e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})